import {
	downTxtNovel
} from "@/api/index.js"
import {
	requestUrl
} from "@/common/config.js"
import fileApi from "@/uni_modules/hbh-fileIo/js_sdk/index.js"
import {
	getLocalNovelContent
} from "@/common/documentFilesplitContent.js"

function downLoad(state, val) {
	val.isStart = true
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(
			fileApi.golabelUrl +
			'documents/downloadTxt/' + val.fileName + '/',
			(
				entry) => {
				//读取这个目录对象
				var directoryReader = entry.createReader();
				//读取这个目录下的所有文件
				directoryReader.readEntries((entries) => {
					//如果有才操作
					if (entries.length > 0) {
						//不删除目录，只删除文件
						let arr=entries.filter(item=>item.name != 'picture.txt')
						arr.forEach((item,index)=>{
							item.remove()
						})
					}
					//后端下载文件接口

					let picurl = requestUrl + '/downTxtNovel'
					// 参数(文件名称)

					// let name = 'myapp.apk'

					let datas = {

						//自定义下载文件路径，保存文件路径仅支持以"_downloads/"、"_doc/"、"_documents/"开头的字符串

						filename:'_documents/downloadTxt/' + val.fileName +'/',

						//默认为GET请求。注意这里需大写“GET”、“POST”

						method: 'POST',
						timeout: 3,
						retry: 1,
						retryInterval: 5,
						data: JSON.stringify({
							fileName: val.fileName,
							bookInfo: val.bookInfo
						})
					}
					// console.log(JSON.stringify({
					// 	fileName: val.fileName,
					// 	bookInfo: val.bookInfo
					// }))
					let dtask = plus.downloader.createDownload(

						picurl,
						datas,

						async (d, status) => {

							// 已响应结果
							if (status == 200) {
								// let apkSrc =
								// 	plus.io
								// 	.convertLocalFileSystemURL(
								// 		d
								// 		.filename)
								// console.log(apkSrc)

								//小说内容切割
								const resp =
									await getLocalNovelContent(
										val
										.fileName, val
										.bookInfo.split(
											"-hbh-")[0])

								console.log(resp.msg)
								val.isStart = false
								val.isDownSuccess = true
								uni.setStorageSync(
									"novelList", JSON
									.stringify(state
										.downTxtLoad
									))
								resolve({
									code: 200,
									msg: "成功"
								})
								dtask.clear()

							} else {
								//重连三次都不行就弹出提示，服务器挂了或者自己没网络了
								console.log("下载失败")
								uni.showModal({
									title: '温馨提示',
									content: '先检查手机网络信号是否良好，网络恢复后重新尝试，否则可能是服务器已停止工作，那就请耐心等待工作人员恢复！感谢配合',
									success: function(
										res
									) {
										if (res
											.confirm
										) {
											console
												.log(
													'用户点击确定'
												);
										} else if (
											res
											.cancel
										) {
											console
												.log(
													'用户点击取消'
												);
										}
									}
								});
								clearInterval(state.timer)
								state.timer=null
								val.isStart = false
								val.isDownSuccess = false
								resolve({
									code: 400,
									msg: "失败"
								})
								dtask.clear()
							}
						}

					)
					dtask.setRequestHeader("Authorization", 'Bearer ' + uni
						.getStorageSync(
							"TOKEN")
					) //post请求，需要自定义header里一些字段，携带token啥的
					dtask.addEventListener('statechanged', (task) => {

						if (!dtask) {
							return;
						}
						switch (task.state) {
							case undefined:
								console.log('下载任务未开始');
								break;

							case 0:
								console.log('下载任务开始调度');
								break;
							case 1:
								console.log('下载任务开始请求');
								break;
							case 2:
								console.log(
									'下载任务网络连接已建立，服务器返回响应，准备传输数据内容'
								);
								//这里可以弹出下载进度框了
								break;
							case 3:
								val.totalSize = (task
										.totalSize /
										1024 / 1024)
									.toFixed(
										2
									)
								val.downingSize =
									(task.downloadedSize /
										1024 /
										1024
									)
									.toFixed(
										2
									)
								val.process =
									parseInt(
										Number(
											(task
												.downloadedSize /
												task
												.totalSize
											) *
											100
										)
									)
								break;
							case 4:
								cnosole.log('下载任务已完成');

								break;
							case 5:
								cnosole.log('下载任务已暂停');

								break;

						}

					});

					// 开始下载

					dtask.start()
				})
			})
	})
}
export default {
	namespaced: true, //命名空间必须写
	state: {
		homeIsLoad: false,
		downTxtLoad: [], //下载队列
		timer: null,
		homeIsRush: false
	},
	getters: {

	},
	//唯一修改state值的方法 
	// commit
	mutations: {
		//通知首页txt专区刷新
		rushHomeTxtBox(state) {
			state.homeIsRush = !state.homeIsRush
		},
		//删除队列信息
		deleteDownList(state, val) {
			let index = state.downTxtLoad.findIndex(item => item.fileName == val.fileName)
			// console.log(index, val)
			if (index != -1) {
				state.downTxtLoad.splice(index, 1)
				uni.setStorageSync("novelList", JSON.stringify(state.downTxtLoad))
				// console.log(state.downTxtLoad, index)
			}else{
				//这是在真机调试的时候防止删除不成功，因为调试时vuex会被清空找不到了
				if (uni.getStorageSync("novelList")) {
					// console.log(JSON.parse(uni.getStorageSync("novelList")))
					let arr = JSON.parse(uni.getStorageSync("novelList"))
					let index2 = arr.findIndex(item => item.fileName == val.fileName)
					if (index2 != -1) {
						arr.splice(index, 1)
						uni.setStorageSync("novelList", JSON.stringify(arr))
					}
				}
			}
			
		},
		//修改队列信息
		putDownList(state, val) {
			let index = state.downTxtLoad.findIndex(item => item.fileName == val.fileName)
			if (index != -1) {
				state.downTxtLoad[index] = val
				uni.setStorageSync("novelList", JSON.stringify(state.downTxtLoad))
			}
		},
		initDownTxtLoad(state) {
			if (uni.getStorageSync("novelList")) {
				// console.log(JSON.parse(uni.getStorageSync("novelList")))
				state.downTxtLoad = JSON.parse(uni.getStorageSync("novelList"))
			}
		},
		//添加到下载队列
		addDownLoad(state, val) {
			state.downTxtLoad = val
			uni.setStorageSync("novelList", JSON.stringify(state.downTxtLoad))
			if (state.timer == null) {
				let loading = -1
				state.timer = setInterval(async () => {
					let index = state.downTxtLoad.findIndex(item => item.isDownSuccess ==
						false)
					if (index != -1) {
						if (index == loading) {
							console.log("正在进行下载中！")
						} else {
							loading = index
							try {
								const res = await downLoad(state, state.downTxtLoad[
									index])
								console.log(res)
								if (res.code == 200) {
									uni.setStorageSync("novelList", JSON.stringify(
										state
										.downTxtLoad))
									loading = -1
								}
								//规定只能一个一个下载,先找出下载的那个的下标
							} catch (e) {
								state.downTxtLoad.splice(index, 1)
								uni.setStorageSync("novelList", JSON.stringify(state
									.downTxtLoad))
								loading = -1
							}
						}

					} else {
						console.log("下载任务为空！")
						clearInterval(state.timer)
						state.timer = null
						return
					}

				}, 1000)
			} else {
				console.log("存在就不创建啊！")
			}
		},
		//开启下载任务队列
		startDownLoad(state) {
			if (state.timer == null) {
				let loading = -1
				state.timer = setInterval(async () => {
					let index = state.downTxtLoad.findIndex(item => item.isDownSuccess == false)
					if (index != -1) {
						if (index == loading) {
							console.log("已经再下载了！")
						} else {
							loading = index
							try {
								const res = await downLoad(state, state.downTxtLoad[index])
								// console.log(res)
								if (res.code == 200) {
									uni.setStorageSync("novelList", JSON.stringify(state
										.downTxtLoad))
									loading = -1
								}
								//规定只能一个一个下载,先找出下载的那个的下标
							} catch (e) {
								state.downTxtLoad.splice(index, 1)
								uni.setStorageSync("novelList", JSON.stringify(state
									.downTxtLoad))
								loading = -1
							}
						}
					} else {
						// console.log("下载任务为空！")
						clearInterval(state.timer)
						state.timer = null
						return
					}
				
				}, 1000)	
			}
		},
		//将base64图片数据保存到本地的txt文件里
		saveJpgTOtxt(state, {
			fileNameId,
			txtPicture
		}) {
			// 请求本地文件系统对象
			plus.io.requestFileSystem(
				plus.io.PUBLIC_DOCUMENTS, // 文件系统中的根目录
				fs => {
					// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象
					fs.root.getFile(`downloadTxt/${fileNameId}/base64/picture.txt`, {
						create: true // 文件不存在则创建
					}, fileEntry => {
						// 文件在手机中的路径
						fileEntry.createWriter(writer => {
							// 写入文件成功完成的回调函数
							writer.onwrite = e => {
								console.log("picture.txt写入数据成功");
								//再次将描述内容也写入一个txt文件里
							};
							// 写入数据
							writer.write(txtPicture);
						})
					}, e => {
						console.log("getFile failed: " + e.message);
					});
				},
				e => {
					console.log(e.message);
				}
			);
		},
		//将小说简介数据保存到本地的txt文件里
		saveDescribeTOtxt(state, {
			fileNameId,
			descrie
		}) {
			// 请求本地文件系统对象
			plus.io.requestFileSystem(
				plus.io.PUBLIC_DOCUMENTS, // 文件系统中的根目录
				fs => {
					// 创建或打开文件, fs.root是根目录操作对象,直接fs表示当前操作对象,同级会不生效，多加了层目录
					fs.root.getFile(`downloadTxt/${fileNameId}/describe/describe.txt`, {
						create: true // 文件不存在则创建
					}, fileEntry => {
						// 文件在手机中的路径
						fileEntry.createWriter(writer => {
							// 写入文件成功完成的回调函数
							writer.onwrite = e => {
								console.log("describe.txt写入数据成功");
							};
							// 写入数据
							writer.write(descrie);
						})
					}, e => {
						console.log("getFile failed: " + e.message);
					});
				},
				e => {
					console.log(e.message);
				}
			);
		}

	},
	// 异步的操作
	// dispatch
	actions: {

	}
}